package com.qiguliuxing.dts.admin.controller;

import static com.qiguliuxing.dts.admin.support.AdminResponseCode.ADMIN_INVALID_OLD_PASSWORD;

import com.qiguliuxing.dts.common.constant.ApiAdminConsts;
import com.qiguliuxing.dts.core.annotation.aoplog.WebLog;
import com.qiguliuxing.dts.service.base.DtsAdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.qiguliuxing.dts.admin.support.AdminResponseUtils;
import com.qiguliuxing.dts.core.support.JacksonUtil;
import com.qiguliuxing.dts.common.util.ResponseUtils;
import com.qiguliuxing.dts.common.util.bcrypt.BCryptPasswordEncoder;
import com.qiguliuxing.dts.db.domain.DtsAdmin;

@RestController
@RequestMapping("/admin/profile")
@Validated
@Api(tags = ApiAdminConsts.Profile.PARENT)
public class AdminProfileController {
	private static final Logger logger = LoggerFactory.getLogger(AdminProfileController.class);

	@Autowired
	private DtsAdminService adminService;

	@RequiresAuthentication
	@PostMapping("/password")
	@ApiOperation(value = ApiAdminConsts.Profile.UPDATE_PWD)
	@WebLog(description = ApiAdminConsts.Profile.UPDATE_PWD,persistence = true)
	public Object create(@RequestBody String body) {
		String oldPassword = JacksonUtil.parseString(body, "oldPassword");
		String newPassword = JacksonUtil.parseString(body, "newPassword");
		if (StringUtils.isEmpty(oldPassword)) {
			return ResponseUtils.badArgument();
		}
		if (StringUtils.isEmpty(newPassword)) {
			return ResponseUtils.badArgument();
		}

		Subject currentUser = SecurityUtils.getSubject();
		DtsAdmin admin = (DtsAdmin) currentUser.getPrincipal();

		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		if (!encoder.matches(oldPassword, admin.getPassword())) {
			logger.info("系统管理->修改密码 错误:{}", ADMIN_INVALID_OLD_PASSWORD.desc());
			return AdminResponseUtils.fail(ADMIN_INVALID_OLD_PASSWORD);
		}

		String encodedNewPassword = encoder.encode(newPassword);
		admin.setPassword(encodedNewPassword);

		adminService.updateById(admin);
		return ResponseUtils.ok();
	}
}
